﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace ComputerShopE3.Controllers
{
    [Serializable]
    [Flags]
    public enum SiteRoles
    {
        Member = 1,
        Employee = 2,
        Admin = 4,
    }
    public class SpiderE3AuthorizeAttribute : AuthorizeAttribute
    {
        // the "new" must be used here because we are overriding
        // the Roles property on the underlying class
        public new SiteRoles Roles;

        public static SiteRoles GetCurrentRole(HttpContextBase httpContext)
        {
            SiteRoles Roles = 0;
            try
            {
                HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                string szRole = authTicket.UserData;
                Roles = (SiteRoles)int.Parse(szRole);
            }
            catch
            {
            }
            return Roles;
        }
        public static SiteRoles GetCurrentRole(HttpContext httpContext)
        {
            SiteRoles Roles = 0;
            try
            {
                HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                string szRole = authTicket.UserData;
                Roles = (SiteRoles)int.Parse(szRole);
            }
            catch
            {
            }
            return Roles;
        }

        public static string GetRoleName(SiteRoles role)
        {
            switch (role)
            {
                case SiteRoles.Member:
                    return "Member";
                case SiteRoles.Employee:
                    return "Employee";
                case SiteRoles.Admin:
                    return "Admin";
                default:
                    return "UNKNOWN";
            }
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            SiteRoles role = 0;
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            role = GetCurrentRole(httpContext);
            //role = (SiteRoles)httpContext.Session["role"];

            if (Roles != 0 && (Roles & role) == 0)
                return false;
            return true;
        }
    }
}
